"use strict";
/**
 * 创建菜单按钮服务
 * Created by liamjung on 2018/6/28.
 */
const AbstractService = require("../abstract_service");
const {getMpConfig} = require("@libfintech/api-gateway-core/util/util");

async function optimizeMenuButton(button, logger) {

    let miniProgramId = button.miniProgramId;

    if (!miniProgramId)
        return;

    let miniProgramConfig = await getMpConfig(miniProgramId);

    if (!miniProgramConfig) {
        //配置不存在时，抛出异常

        logger.warn("There is no mini program (mpId: " + miniProgramId + ") config");

        return;
    }

    delete button.miniProgramId;
    button.appid = miniProgramConfig.appId;
}

class MenuBtnService extends AbstractService {

    /**
     * 执行
     * @param dto       MenuBtnDTO
     * @param mpConfig  公众号配置
     * @param pipeline  管道
     * @returns {Promise.<void>}
     */
    async execute(dto, mpConfig, pipeline) {

        for (let button of dto.button) {
            if (button.url && button.url.trim().length > 0 && button.isEncodeUrl)
                button.url = this.oauth2buildAuthorizationUrl(button.url, "snsapi_base", "STATE");

            await optimizeMenuButton(button, pipeline.logger);

            if (button.sub_button) {
                for (let subButton of button.sub_button) {

                    if (subButton.url && subButton.url.trim().length > 0 && subButton.isEncodeUrl)
                        subButton.url = this.oauth2buildAuthorizationUrl(subButton.url, "snsapi_base", "STATE");

                    await optimizeMenuButton(subButton, pipeline.logger);
                }
            }
        }

        super.updateRequest(pipeline.request, undefined, dto);
    }
}

module.exports = new MenuBtnService();